package com.tsing.common.utils;

import org.springframework.cglib.beans.BeanCopier;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

public class BeanCoperUtil {

    //转单个m是原对象，T是转换后的对象
    public static <T, M> T copyProperties(M source, Class<T> clazz, BeanCopier copier) {
        if (null == copier) {
            copier = BeanCopier.create(source.getClass(), clazz, false);
        }
        T t = null;
        try {
            t = clazz.newInstance();
            copier.copy(source, t, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return t;
    }

    //多个列表转换
    public static <T, M> List<T> copyObjects(List<M> sources, Class<T> clazz) throws Exception {
        if (Objects.isNull(sources) || Objects.isNull(clazz) || sources.isEmpty()) {
            throw new IllegalArgumentException();
        }
        BeanCopier copier = BeanCopier.create(sources.get(0).getClass(), clazz, false);
        return Optional.of(sources).orElse(new ArrayList<>()).stream().map(m -> copyProperties(m, clazz, copier)).collect(Collectors.toList());
    }

}
